package com.maodou.core.ui.components

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.intl.Locale
import androidx.compose.ui.text.toUpperCase
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import coil3.compose.AsyncImage
import coil3.compose.AsyncImagePainter
import coil3.compose.SubcomposeAsyncImage
import coil3.compose.SubcomposeAsyncImageContent
import coil3.compose.SubcomposeAsyncImageScope

/**
 * 常用图片组件封装：
 * - AppAsyncImage：简单的异步图片加载（支持占位/错误/裁剪）
 * - AppAsyncImageWithState：暴露加载/成功/失败状态插槽
 * - AvatarImage：头像（圆形/可裁剪/占位首字母）
 */

@Composable
fun AppAsyncImage(
    model: Any?,
    contentDescription: String? = null,
    modifier: Modifier = Modifier,
    contentScale: ContentScale = ContentScale.Crop,
    placeholderRes: Int? = null,
    errorRes: Int? = null,
) {
    AsyncImage(
        model = model,
        contentDescription = contentDescription,
        contentScale = contentScale,
        modifier = modifier,
        placeholder = placeholderRes?.let { painterResource(id = it) },
        error = errorRes?.let { painterResource(id = it) },
    )
}

@Composable
fun AppAsyncImageWithState(
    model: Any?,
    contentDescription: String?,
    modifier: Modifier = Modifier,
    placeholderRes: Int? = null,
    contentScale: ContentScale = ContentScale.Crop,
    loading: @Composable SubcomposeAsyncImageScope.(AsyncImagePainter.State.Loading) -> Unit = {
        Box(modifier = Modifier.matchParentSize(), contentAlignment = Alignment.Center) {
            CircularProgressIndicator(color = MaterialTheme.colorScheme.primary)
        }
    },
    error: @Composable SubcomposeAsyncImageScope.(AsyncImagePainter.State.Error) -> Unit = {
        // 默认错误状态占位
        Box(
            modifier = Modifier
                .matchParentSize()
                .background(MaterialTheme.colorScheme.surfaceVariant),
            contentAlignment = Alignment.Center
        ) {
            // 可以放置错误图标或文本
            placeholderRes?.let {
                Icon(
                    painter = painterResource(id = placeholderRes),
                    contentDescription = contentDescription,
                    tint = Color.Unspecified,
                    modifier = modifier
                )
            }
        }
    },
    success: @Composable SubcomposeAsyncImageScope.(AsyncImagePainter.State.Success) -> Unit = {
        SubcomposeAsyncImageContent()
    }
) {
    SubcomposeAsyncImage(
        model = model,
        contentDescription = contentDescription,
        modifier = modifier,
        contentScale = contentScale,
        loading = loading,
        error = error,
        success = success
    )
}

@Composable
fun AvatarImage(
    model: Any?,
    size: Dp = 48.dp,
    contentDescription: String? = null,
    backgroundColor: Color = MaterialTheme.colorScheme.surfaceVariant,
    contentColor: Color = MaterialTheme.colorScheme.onSurface,
    placeholderText: String? = null,
) {
    val shape = CircleShape

    if (model == null && !placeholderText.isNullOrBlank()) {
        // 首字母占位（简易实现：Text 叠加，避免外部额外资源）
        Box(
            modifier = Modifier
                .size(size)
                .clip(shape)
                .background(backgroundColor),
            contentAlignment = Alignment.Center
        ) {
            AppText(
                text = placeholderText.first().toString().toUpperCase(Locale.current),
                color = contentColor,
                style = MaterialTheme.typography.titleMedium
            )
        }
    } else {
        AsyncImage(
            model = model,
            contentDescription = contentDescription,
            modifier = Modifier
                .size(size)
                .clip(shape),
            contentScale = ContentScale.Crop
        )
    }
}

@Preview
@Composable
private fun ImagePreview() {
    Box(modifier = Modifier.size(120.dp)) {
        AppAsyncImageWithState(
            model = "https://images.unsplash.com/photo-1522075469751-3a6694fb2f61?w=512",
            contentDescription = "preview",
        )
    }
}